import 'package:dailoz/enum/create_task_enum.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/service/tag_service/tag_service.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/input_utils.dart';
import 'package:dailoz/utils/showAlertDialog.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/view_model/add_page_view_model.dart';
import 'package:dailoz/views/home.dart';
import 'package:dailoz/widgets/button_widget.dart';
import 'package:dailoz/widgets/date_picker_item.dart';
import 'package:dailoz/widgets/dialog.dart';
import 'package:dailoz/widgets/progress_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class AddPage extends StatefulWidget {
  const AddPage({Key? key, this.date, this.time}) : super(key: key);

  static String id = "addPageId";
  final DateTime? date;
  final String? time;

  @override
  State<AddPage> createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> {
  TextEditingController? titleController;
  TextEditingController? desController;
  TextEditingController? tagNameController;

  String groupValue = "normal";

  late AddPageViewModel _addPageViewModel;

  @override
  void initState() {
    super.initState();
    titleController = TextEditingController();
    desController = TextEditingController();
    tagNameController = TextEditingController();
    _addPageViewModel = context.read<AddPageViewModel>();
    _addPageViewModel.fetchTagList();
    _addPageViewModel.format(widget.date, widget.time);
  }

  @override
  void dispose() {
    super.dispose();
    // TagService.changeUserTag();
    titleController!.dispose();
    desController!.dispose();
    tagNameController!.dispose();
    InputUtil.clear();
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<AddPageViewModel>(context);
    // provider.format(widget.date, widget.time);
    return ProgressWidget(
      loading: provider.isLoading,
      msg: S.of(context).isLoading,
      child: Scaffold(
        body: SingleChildScrollView(
          child: Stack(
            children: [
              Positioned(
                top: SizeConfig.getProportionateScreenHeight(56.0),
                left: SizeConfig.getProportionateScreenWidth(30.0),
                child: Container(
                  height: SizeConfig.getProportionateScreenHeight(42.0),
                  width: SizeConfig.getProportionateScreenWidth(42.0),
                  decoration: const BoxDecoration(
                    // color: Theme.of(context).buttonColor,
                    borderRadius: BorderRadius.all(
                      Radius.circular(14.0),
                    ),
                  ),
                  child: IconButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    icon: Icon(
                      Icons.arrow_back_ios_outlined,
                      color: Theme.of(context).textTheme.bodyText2?.color,
                      size: SizeConfig.getProportionateFontSize(14.0),
                    ),
                  ),
                ),
              ),
              Center(
                child: SizedBox(
                  width: SizeConfig.getProportionateScreenWidth(327.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(top: 68.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              S.of(context).addTask,
                              style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                    fontSize: SizeConfig.getProportionateFontSize(18.0),
                                    fontWeight: FontWeight.w500,
                                  ),
                            ),
                          ],
                        ),
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).title,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: SizeConfig.getProportionateScreenHeight(35.0),
                            child: TextField(
                              controller: titleController,
                            ),
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).date,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: SizeConfig.getProportionateScreenHeight(35.0),
                            child: DatePickerItem(
                              children: <Widget>[
                                Text(
                                  '${provider.date.year}-${provider.date.month.toString().padLeft(2, "0")}-${provider.date.day.toString().padLeft(2, "0")}',
                                  style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                        fontSize: SizeConfig.getProportionateFontSize(16.0),
                                      ),
                                ),
                                IconButton(
                                  // Display a CupertinoDatePicker in time picker mode.
                                  onPressed: () => ShowDialog.showDialog(
                                    context,
                                    CupertinoDatePicker(
                                      initialDateTime: provider.date,
                                      mode: CupertinoDatePickerMode.date,
                                      use24hFormat: true,
                                      // This is called when the user changes the time.
                                      onDateTimeChanged: (DateTime newTime) {
                                        setState(() => provider.changeDate(newTime));
                                      },
                                    ),
                                  ),
                                  icon: Icon(
                                    Icons.calendar_month_outlined,
                                    color: const Color(0xff10275a),
                                    size: SizeConfig.getProportionateFontSize(20.0),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).time,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          Row(
                            children: [
                              SizedBox(
                                width: SizeConfig.getProportionateScreenWidth(147.0),
                                child: DatePickerItem(
                                  rowMainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    TextButton(
                                      onPressed: () {
                                        ShowDialog.showDialog(
                                          context,
                                          CupertinoDatePicker(
                                            initialDateTime: provider.startTime,
                                            mode: CupertinoDatePickerMode.time,
                                            onDateTimeChanged: (newTime) {
                                              provider.changeStartTime(newTime);
                                            },
                                          ),
                                        );
                                      },
                                      child: Text(
                                        '${provider.startTime.hour.toString().padLeft(2, "0")}:${provider.startTime.minute.toString().padLeft(2, "0")}',
                                        style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                              fontSize: SizeConfig.getProportionateFontSize(18.0),
                                            ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: SizeConfig.getProportionateScreenWidth(20.0),
                              ),
                              SizedBox(
                                width: SizeConfig.getProportionateScreenWidth(147.0),
                                child: DatePickerItem(
                                  rowMainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    TextButton(
                                      onPressed: () {
                                        ShowDialog.showDialog(
                                          context,
                                          CupertinoDatePicker(
                                            initialDateTime: provider.endTime,
                                            mode: CupertinoDatePickerMode.time,
                                            onDateTimeChanged: (newTime) {
                                              setState(() {
                                                provider.changeEndTime(newTime);
                                              });
                                            },
                                          ),
                                        );
                                      },
                                      child: Text(
                                        '${provider.endTime.hour.toString().padLeft(2, "0")}:${provider.endTime.minute.toString().padLeft(2, "0")}',
                                        style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                              fontSize: SizeConfig.getProportionateFontSize(18.0),
                                            ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).description,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: SizeConfig.getProportionateScreenHeight(35.0),
                            child: TextField(
                              controller: desController,
                            ),
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).type,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          Wrap(
                            spacing: SizeConfig.getProportionateScreenWidth(30.0),
                            children: [
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Radio(
                                    value: "normal",
                                    groupValue: groupValue,
                                    onChanged: (value) {
                                      setState(() {
                                        groupValue = value!;
                                      });
                                    },
                                  ),
                                  Text(
                                    "Normal",
                                    style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                          fontSize: SizeConfig.getProportionateFontSize(16.0),
                                        ),
                                  ),
                                ],
                              ),
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Radio(
                                    value: "urgent",
                                    groupValue: groupValue,
                                    onChanged: (value) {
                                      setState(() {
                                        groupValue = value!;
                                      });
                                    },
                                  ),
                                  Text(
                                    "Urgent",
                                    style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                          fontSize: SizeConfig.getProportionateFontSize(16.0),
                                        ),
                                  )
                                ],
                              ),
                            ],
                          )
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 25.0),
                            child: Text(
                              S.of(context).tags,
                              style: TextStyle(
                                fontSize: SizeConfig.getProportionateFontSize(14.0),
                                color: const Color(0xff8a8bb3),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: SizeConfig.getProportionateScreenHeight(22.0),
                          ),
                          Wrap(
                            spacing: SizeConfig.getProportionateScreenWidth(2.0),
                            runSpacing: SizeConfig.getProportionateScreenHeight(22.0),
                            children: provider.generate(),
                          ),
                        ],
                      ),
                      Column(
                        children: <Widget>[
                          Center(
                            child: TextButton(
                              onPressed: () {
                                showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return HtmlDialog(
                                      cancelContent: S.of(context).Cancel,
                                      title: S.of(context).newTag,
                                      content: TextField(
                                        decoration: const InputDecoration(
                                          border: InputBorder.none,
                                          fillColor: Color(0xfff6f6f6),
                                          filled: true, // filled为true后，fillColor才生效
                                        ),
                                        controller: tagNameController!,
                                      ),
                                      confirmContent: S.of(context).confirm,
                                      confirmCallback: () {
                                        TagService.createTag(context, provider, tagNameController);
                                        // createTag(provider);
                                      },
                                      dismissCallback: () {
                                        Navigator.pop(context);
                                      },
                                    );
                                  },
                                );
                              },
                              child: Text(
                                "+ ${S.of(context).addNewTag}",
                                style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                      fontSize: SizeConfig.getProportionateFontSize(
                                        14.0,
                                      ),
                                    ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Padding(
                        padding: EdgeInsets.only(
                          top: SizeConfig.getProportionateScreenHeight(25.0),
                          bottom: SizeConfig.getProportionateScreenHeight(40.0),
                        ),
                        child: ButtonWidget(
                          width: SizeConfig.getProportionateScreenHeight(327.0),
                          height: SizeConfig.getProportionateScreenHeight(56.0),
                          buttonText: S.of(context).addTask,
                          onPressed: () async {
                            Map<String, dynamic> taskInfo = {};
                            taskInfo["taskContent"] = titleController!.text;
                            taskInfo['status'] = 1;
                            taskInfo['type'] = groupValue;
                            taskInfo['description'] = desController!.text;
                            CreateTaskEnum taskEnum = await provider.createTask(taskInfo);
                            switch (taskEnum) {
                              case CreateTaskEnum.taskContentNull:
                                showToast("任务内容不能为空");
                                break;
                              case CreateTaskEnum.tagNull:
                                showToast("请指定至少一个标签");
                                break;
                              case CreateTaskEnum.created:
                                if (!mounted) return;
                                Navigator.of(context).pushNamedAndRemoveUntil(Home.id, (Route<dynamic> route) => false);
                                break;
                              default:
                                break;
                            }
                          },
                          buttonColor: const Color(0xff5b67ca),
                          buttonTextColor: Colors.white,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
